<!-- eslint-disable @typescript-eslint/no-use-before-define -->
<!--
 * @Author       : wfl
 * @LastEditors: zdl
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-01 10:05:50
 * @LastEditTime: 2024-01-11 15:57:54
-->
<script lang="ts" setup name="UserManage">
import { ikArray } from 'iking-utils'
import { useFields } from './fields'
import { userApi } from '@/MainApp/apis/user'
import useUserStore from '@/global/store/modules/user'
import { systemConfig } from '@/system.config'
// 启用组织
const ENABLE_ORGANIZA = systemConfig.organiza?.enable

const userStore = useUserStore()
const organizationIds = computed(() => userStore.userInfo.organizationIds || [])

const UserEditModal = defineAsyncComponent(() => import('./UserEditModal.vue'))
const { t } = useConfig()
const { msgBoxWarnAsync, msgSuccess, msgError, msgBoxInfoAsync } = useMessage()
const { sexList, fieldList } = useFields(ENABLE_ORGANIZA)

// ------------------查询块------------------
const userData = ref([])
const loading = ref(false)
const countTotal = ref(0)
// 组件返回的查询参数，包含分页和查询字段
const pageData = ref()
// 查询
const queryUser = async () => {
  loading.value = true
  const param = {
    ...pageData.value,
    orgId: organizationIds.value[0]
  }

  const { success, data, total, msg } = await userApi.getUserList(param)
  countTotal.value = total
  if (success) {
    data?.length > 0
    && data.forEach((d: any) => {
      const sex = sexList.value?.find((s: { id: string; }) => s.id === d.sex)
      d.sexName
        = sex ? sex?.label : ''
      d.post = d.postList?.map((p: { name: any; }) => p.name) || ''
      d.role = d.roleList?.map((p: { name: any; }) => p.name) || ''
      d.dept = d.deptList?.map((p: { name: any; }) => p.name) || ''
    })
    userData.value = success ? data : []
    loading.value = false
  }
  else {
    msgError(msg)
    loading.value = false
  }
}
// 重置密码
const handResetPassword = (row: any) => {
  msgBoxInfoAsync('重置确认', `重置密码后，用户【 ${row.name} 】的系统登录密码将被设置为默认密码，确定重置吗?`, async () => {
    const { msg, success } = await userApi.resetPassword(row.id)
    if (success)
      msgSuccess(msg)

    else msgError(msg)
  })
}

// ------------------增删改------------------
// 新增、修改
const dialogVisible = ref(false)
const editData = ref()
const handAddUser = () => {
  dialogVisible.value = true
}
const handEditRow = (row: any) => {
  editData.value = row
  dialogVisible.value = true
}
const handCancel = () => {
  editData.value = null
}
// 删除
const handDelete = (row: any) => {
  msgBoxWarnAsync('确认删除', `删除后，用户【${row.name}】将不能使用本系统，无法恢复。确定删除吗？`, async () => {
    const { success, msg } = await userApi.deleteUser(row.id)
    if (success) {
      await queryUser()
      msgSuccess(msg)
    }
    else {
      msgError(msg)
    }
  })
}

// ------------------锁定块------------------
const lockLoading = ref(false)
const lockKey = ref('')
const handLock = async (row: {
  locked: any
  username: string
  id: string
  lockType: any
}) => {
  lockLoading.value = true
  lockKey.value = row.id
  const res = await userApi.lockedUser(row.locked, row.username)
  if (res?.success) {
    await queryUser()
    msgSuccess(res.msg)
  }
  // 修改失败，还原值 PERMANENTLY_LOCK
  else {
    row.locked = !row.locked
    row.lockType = row.locked ? 'PERMANENTLY_LOCK' : 'NO_LOCK'
  }

  lockLoading.value = false
  lockKey.value = ''
}

// 组织数据
const treeDeptData: any = ref([])
useDep().then(res => {
  treeDeptData.value = res
})
// 选择部门
const sectionSlectChange = async (val: any) => {
  pageData.value.deptId = val
  await queryUser()
}
const { setColor } = useTagColor()
const formatList = (list: any) => {
  return setColor(typeof list === 'string' ? list.split(',') : list)
}
// ------------------其它 ------------------
// 获取性别名称
const getName = (key?: string) => {
  const sex = sexList.value?.find((s: { value: string; }) => s.value === key)
  return sex ? sex?.label : ''
}
const _judgeRole = judgeRole
</script>

<template>
  <IkPageMain fixed>
    <IkPageFull
      v-model="pageData"
      header-title="用户列表"
      :fields="fieldList"
      :table-data="userData"
      :total="countTotal"
      :loading="loading"
      :search="queryUser"
      stripe
    >
      <!-- 搜索slot -->
      <template #headerRight>
        <el-button v-role="'$ADD-USER'" type="primary" @click="handAddUser">{{ t('user.add') }}</el-button>
      </template>
      <template #deptId="autoForm">
        <el-select
          v-model="autoForm.value.deptId"
          placeholder="请选择部门"
          clearable
          @change="sectionSlectChange"
        >
          <el-option
            v-for="item in treeDeptData"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </template>
      <!-- 表格solt -->
      <template #name="{ data }">
        <IkSideText
          :avatar="data.row.avatar"
          :name="data.row.name"
          :text="data.row.name"
          :sub-text="ikArray.listToString(data?.row.departments, 'deptName', ',') "
        />
      </template>
      <template #sex="{ data }">
        {{ getName(data.row.sex) }}
      </template>
      <template #post="{ data }">
        <IkStatuOver :list="formatList(ikArray.listToString(data.row?.posts, 'postName', ','))" />
      </template>
      <template #role="{ data }">
        <!-- <IkStatuOver :list="formatList(ikArray.listToString(data.row?.roles, 'roleName', ','))" /> -->
        {{ ikArray.listToString(data.row?.roles, 'roleName', ', ') }}
      </template>
      <template #locked="{ data }">
        <!-- && data.row.lockType !== 'PERMANENTLY_LOCK' -->
        <el-switch
          v-if="_judgeRole('LOCK-USER') "
          v-model="data.row.locked"
          :loading="lockLoading && lockKey === data.row.id"
          inline-prompt
          @change="handLock(data.row)"
        />
        <IkStatu v-else :title="data.row.lockTypeName" :type="(data.row.locked || data.row.lockType === 'PERMANENTLY_LOCK') ? 'warning' : 'success'" />
      </template>
      <template #operate="{ data }">
        <IkBtnContent :num="3">
          <IkSvgIcon
            v-role="'UPDATE-USER'"
            name="icon-bianji"
            type="info"
            show-bg
            in-table
            pop
            :start-margin="false"
            :title="t('action.modify')"
            @click="handEditRow(data.row)"
          />
          <IkSvgIcon
            v-role="'DELETE-USER'"
            name="icon-shanchu"
            show-bg
            in-table
            pop
            :title="t('action.delete')"
            type="danger"
            @click="handDelete(data.row)"
          />
          <IkSvgIcon
            v-role="'USER-RESET-PASSWORD'"
            name="icon-shuaxin"
            show-bg
            in-table
            pop
            :title="`${t('action.reset')}${t('app.password')}`"
            @click="handResetPassword(data.row)"
          />
        </IkBtnContent>
      </template>
    </IkPageFull>
    <UserEditModal
      v-model:visible="dialogVisible"
      destroy-on-close
      :edit-data="editData"
      @cancel="handCancel"
      @confirm="queryUser"
    />
  </IkPageMain>
</template>

<style lang="scss" scoped>
.user-cen{
  display: flex;
  justify-content: flex-start;
  line-height: 40px;

  .user-text{
    margin-left: 10px;
  }
}
</style>
